import time

from flask import Blueprint, request, Response, redirect
from flask_login import login_required

from swaager_init import siwa
from cache import redis_cli
from tools.ali_pay import alipay
from tools.tools import my_route
from flask_siwadoc import BaseModel

order = siwa.blueprint('order', __name__, tags=['order'], group='order')


@order.route('/house/<int:h_id>', methods=['POST'], body=BaseModel)
def add_order(h_id):
    return 'Hi'


@order.route('/house/<int:h_id>', methods=['GET'], group='ss')
def get_orders(h_id):
    # 获取当前房子所有订单
    # 今天以后
    with open('flask.log', 'ab') as f:
        if request.args.get('r'):
            # f.write(f'loggr:ad_test {h_id} 这个房间报错了 广告页\n'.encode('utf-8'))
            current_app.logger.info(f'loggr:ad_test {h_id} 这个房间报错了 广告页')
        else:
            f.write(f'loggr:ad_test {h_id} 这个房间报错了 原始页\n'.encode('utf-8'))
            # current_app.logger.info(f'loggr:ad_test {h_id} 这个房间报错了 原始页')
    return '222'


@order.route('/<int:o_id>', methods=['PUT'])
def put_order(o_id):
    # 拿到房东操作的一个字段
    # 修改订单状态
    type_ = request.args.get('type')
    if type_ == 'ali':
        return redirect('http://127.0.0.1:9527/order/')
    elif type_ == 'wechat':
        return redirect('http://127.0.0.1:9527/order/')
    return my_route(200)


# query: Optional[Type[BaseModel]] = None,
# header: Optional[Type[BaseModel]] = None,
# cookie: Optional[Type[BaseModel]] = None,
# body: Optional[Type[BaseModel]] = None,
# form: Optional[Type[BaseModel]] = None,
# files = None,
# resp = None,
# x = [],
# tags = [],
# group = None,
# summary = None,
# description = None,
class AddHouse(BaseModel):
    title: str
    info: str
    zheng: bool = True
    p_num: int
    c_num: int
    live: bool = True
    city: str
    price: int


# 订单支付
@order.route('/<int:o_id>/ali', methods=['get'])
def order_pay(o_id):
    # global start_t
    # print(start_t)
    # new_t = time.time()
    # if new_t < start_t + 1:
    #     time.sleep(start_t + 1-new_t)
    #     print(start_t)
    # start_t = time.time()
    ali_ret = alipay.client_api(
        "alipay.trade.page.pay",
        biz_content={
            "out_trade_no": o_id,
            "total_amount": 1.1,
            "subject": "中文也没问题",
            "product_code": "FAST_INSTANT_TRADE_PAY",
        },
        return_url=f"http://127.0.0.1:9527/order/{o_id}?type=ali",  # this is optional
    )
    redis_cli.lpush('ali_order', str(o_id) + '/' + ali_ret)

    # return redirect('https://openapi.alipaydev.com/gateway.do?'+ali_ret)
    return str(time.time())
